package com.atldy.commerce.service;

import cn.hutool.json.JSONUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

/**
 * @version 1.0
 * @Author: lidongyang
 * @CreateTime: 2021-07-31 18:51
 * @Description：
 */
@Service
@Slf4j
public class NacosClientService {

    private final DiscoveryClient discoveryClient;

    public NacosClientService(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }

    public List<ServiceInstance> getServiceInstance(String serviceId) {
        log.info("服务名称是：{}", serviceId);
        return discoveryClient.getInstances(serviceId);
    }

    public List<List<ServiceInstance>> getNacosClientInfos(List<String> serviceIds) {
        log.info("请求参数的服务实例名称是：[{}]", JSONUtil.toJsonStr(serviceIds));
        List<List<ServiceInstance>> services = new ArrayList<>();
        serviceIds.forEach(s -> services.add(discoveryClient.getInstances(s)));
        return services;
    }

    /**
     * <h3>请求合并</h3>
     */
    @HystrixCollapser(batchMethod = "findNacosClientInfos"
            , scope = com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL
            , collapserProperties = {
            @HystrixProperty(name = "timerDelayInMilliseconds", value = "300")
    })
    public Future<List<ServiceInstance>> findNacosClientInfo(String s) {
        throw new RuntimeException("注解请求出现异常");
    }

    @HystrixCommand
    public List<List<ServiceInstance>> findNacosClientInfos(List<String> serviceIds) {
        return this.getNacosClientInfos(serviceIds);
    }

}